package configurator;

import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Configurator {
	private File confFile;
	private SettingOfServer settings;

	public Configurator() {
		this("ServerData/configurator.xml");
	}

	public Configurator(String s) {		
		settings = new SettingOfServer();
		if (s.endsWith(".xml")) {
			confFile = new File(s);
			if (!(confFile.exists())) {
				try {
					confFile.createNewFile();
					write();
				} catch (IOException e) {
					System.err.println(e);
				}
			}
		}
		read();
	}

	public File getConfFile() {
		return confFile;
	}

	public void setConfFile(File confFile) {
		this.confFile = confFile;
	}

	public SettingOfServer getSettings() {
		return settings;
	}

	public void setSettings(SettingOfServer settings) {
		this.settings = settings;
		write();
	}

	public void read() {
		try {
			JAXBContext jaxbContext = JAXBContext
					.newInstance(SettingOfServer.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			settings = (SettingOfServer) jaxbUnmarshaller.unmarshal(confFile);
		} catch (JAXBException e) {
			System.err.println(e);
		}
	}

	private void write() {
		try {
			JAXBContext jaxbContext = JAXBContext
					.newInstance(SettingOfServer.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			jaxbMarshaller.marshal(settings, confFile);
		} catch (JAXBException e) {
			System.err.println(e);
		}		
	}
}